//
//  VideoPicker.swift
//  ptbuy
//
//  Created by MyMac on 2024/11/14.
//
/**
  视频录像
 */
import SwiftUI
import UIKit

// MARK: - UIImagePickerController wrapper for SwiftUI
struct VideoPicker: UIViewControllerRepresentable {
    class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
        var parent: VideoPicker

        init(parent: VideoPicker) {
            self.parent = parent
        }

        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
            
            
            if let mediaURL = info[.mediaURL] as? URL {
                // Return the video URL to parent
                
                let fileName = UUID().uuidString.replacingOccurrences(of: "-", with: "")+".mov"
                
                
                let destinationURL = Utils.getDocumentsDirectory().appendingPathComponent(fileName)
                    do {
                        try FileManager.default.copyItem(at: mediaURL, to: destinationURL)
                        parent.medias.append(fileName)
                        parent.video=parent.video+1
                        print("视频保存成功")
                    } catch {
                        print("保存视频失败: \(error)")
                    }
                
            }
            parent.isPresented = false
        }

        func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
            parent.isPresented = false
        }
    }

    @Binding var isPresented: Bool
    @Binding var medias:[String]
    @Binding var video:Int8//记录已有视频数

    func makeCoordinator() -> Coordinator {
        return Coordinator(parent: self)
    }

    func makeUIViewController(context: Context) -> UIImagePickerController {
        let picker = UIImagePickerController()
        picker.delegate = context.coordinator
        picker.sourceType = .camera
        picker.mediaTypes = ["public.movie"] // Only video media type
        picker.cameraCaptureMode = .video
        picker.allowsEditing = false // Set to true if you want to allow video trimming
        return picker
    }

    func updateUIViewController(_ uiViewController: UIImagePickerController, context: Context) {
        // Not needed in this case
    }
}
